package com.itheima.health.security;

import ch.qos.logback.core.pattern.color.ANSIConstants;
import com.alibaba.fastjson.JSON;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Permission;
import com.itheima.health.pojo.Role;
import com.itheima.health.pojo.User;
import com.sun.org.apache.bcel.internal.generic.NEW;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author ：石破天
 * @date ：Created in 2022/6/3
 * @description ：
 * @version: 1.0
 */
@Slf4j
							//过滤器拦截所有的后端请求
@WebFilter(urlPatterns = "/*")
public class HealthSecurityFilter implements Filter {

    //设置白名单   不需要登录请求的路径
    private String[] unLoginAccessUrlList = new String[]{
            "/user/login",
            "/user/logout",
            "/common/**",
            "/mobile/**",};

    private Map<String, String> loginAuthUrlMap = new HashMap<>();

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

        //请求路径需要对应的权限
        // 读取资源需要的权限 initAuthUrlMap(); // 权限列表
        initAuthUrlMap();
    }

    private void initAuthUrlMap() {
        //检查项
        loginAuthUrlMap.put("/checkitem/findPage", "CHECKITEM_QUERY");
        loginAuthUrlMap.put("/checkitem/add", "CHECKITEM_ADD");
        loginAuthUrlMap.put("/checkitem/delete", "CHECKITEM_DELETE");
        loginAuthUrlMap.put("/checkitem/findById", "CHECKITEM_EDIT");
        loginAuthUrlMap.put("/checkitem/edit", "CHECKITEM_EDIT");

        //检查组
        loginAuthUrlMap.put("/checkgroup/findPage", "CHECKGROUP_QUERY");
        loginAuthUrlMap.put("/checkitem/findAll", "CHECKITEM_QUERY");
        loginAuthUrlMap.put("/checkgroup/add", "CHECKGROUP_ADD");
        loginAuthUrlMap.put("/checkgroup/findCheckItemIdsByCheckGroupId", "CHECKITEM_QUERY");
        loginAuthUrlMap.put("/checkgroup/edit", "CHECKGROUP_EDIT");
        loginAuthUrlMap.put("/checkgroup/deleteCheckGroupitemById", "CHECKGROUP_DELETE");
        loginAuthUrlMap.put("/checkgroup/findAll", "CHECKITEM_QUERY");

        //套餐
        loginAuthUrlMap.put("/setmeal/findPage", "SETMEAL_QUERY");
        loginAuthUrlMap.put("/setmeal/add", "SETMEAL_ADD");
        loginAuthUrlMap.put("/setmeal/upload", "CHECKITEM_QUERY");

        //预约设置
        loginAuthUrlMap.put("/ordersetting/getOrderSettingByMonth", "ORDERSETTING");
        loginAuthUrlMap.put("/ordersetting/editNumberByDate", "ORDERSETTING");
        loginAuthUrlMap.put("/ordersetting/upload", "ORDERSETTING");
        //TODO
        //统计表
        loginAuthUrlMap.put("/report/**","REPORT_VIEW");

    }


    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
                         FilterChain filterChain) throws IOException, ServletException {

        //拦截所有请求
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setContentType("application/json; charset=UTF-8");
        // 1.获取URI
        String uri = request.getRequestURI();
        log.info("[权限检查过滤器...],当前uri:{}", uri);
        //判断是否是白名单uri
        boolean b = checkURI(uri);
        if (b) {
            //白名单uri请求
            filterChain.doFilter(request, response);   //放行 白名单请求
            return;
        }
        //非白名单uri
        User user = (User) request.getSession().getAttribute("user");
        if (user != null) {
            //已经登录
            //查看uri是否需要权限    校验
            boolean b1 = checkperssanth(uri, user);
            if (b1) {
                //放行
                filterChain.doFilter(request, response);
                return;// 放行
            }
            response.setContentType("application/json;charset=utf-8");
            //请求没有权限
            Result result = new Result(false, "没有权限");
            String string = JSON.toJSONString(result);
            response.getWriter().write(string);

        } else {
            //没有获取到user 没有登录
            response.setContentType("application/json;charset=utf-8");
            Result result = new Result(false, "没有登录");
            String string = JSON.toJSONString(result);
            response.getWriter().write(string);
        }


    }

    //前端的uri和用户的权限校验
    private boolean checkperssanth(String uri, User user) {
        AntPathMatcher matcher = new AntPathMatcher();
        //查看uir是否需要权限   需要权限验证用户权限
        Set<String> Auths = loginAuthUrlMap.keySet();
        String anuri = null;
        for (String authuri : Auths) {
            if (matcher.match(uri, authuri)) {
                //匹配上校验是否需要权限
                anuri = authuri;
            }
        }
        if (anuri == null) {
            return true;   //不要权限就能访问
        }
        //查看用户权限
        Set<Role> roles = user.getRoles();
        for (Role role : roles) {
            Set<Permission> permissions = role.getPermissions();
            for (Permission permission : permissions) {
                if (permission.getKeyword().equals(loginAuthUrlMap.get(anuri))) {
                    return true;
                }
            }
        }
        //    请求需要有用户权限 但没有匹配上
        return false;
    }

    //检验是否是白名单
    private boolean checkURI(String uri) {
        AntPathMatcher antPathMatcher = new AntPathMatcher();   //
        for (String s : unLoginAccessUrlList) {
            if (antPathMatcher.match(s, uri)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void destroy() {

    }

}